
package com.bear.cmcc.NetTestHTTP.ui.activity;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.CityBean;
import com.bear.cmcc.NetTestHTTP.component.json.respond.CountryCityFtpInfoRankRespond;
import com.bear.cmcc.NetTestHTTP.constant.HttpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.ui.adapter.CityTopListAdapter;
import com.bear.cmcc.NetTestHTTP.ui.view.HVListView;
import com.bear.cmcc.NetTestHTTP.ui.view.LoadingDialog;
import com.bear.cmcc.NetTestHTTP.util.CountryUtil;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.SortCityIntSpeed;
import com.bear.cmcc.NetTestHTTP.util.SortCityStringSpeed;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CityTopActivity extends AbstractActivity implements OnClickListener {

    private HVListView mListView;

    private Button mNetTD;

    private Button mNet2G;

    private ArrayList<CityBean> data;

    private CityTopListAdapter cityTopListAdapter;

    private Boolean isTop = true;// 排序的

    private Boolean isTD = true;

    private TextView tvNetSpeed, slide_item_drop_rate, slide_item_signal, slide_item_call_complete;

    private boolean isDrop, isSignal, isComplete;

    int refresh = 1;

    int show = 2;
    
    int clear = 3;

    int total_size_td = HttpConstant.TOTAL_COUNT;

    int total_size_2g = HttpConstant.TOTAL_COUNT;

    Integer service_total_size_td = 0;

    Integer service_total_size_2g = 0;

    int every_size = HttpConstant.TOTAL_COUNT;

    private LoadingDialog dialog;

    private Handler refreshHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == refresh) {
                if (cityTopListAdapter != null) {
                    mListView.setAdapter(cityTopListAdapter);
                    cityTopListAdapter.notifyDataSetChanged();

                    if (isTD) {
                        if (total_size_td > every_size) {
                            mListView.setSelection(total_size_td - every_size);
                        }
                    } else {
                        if (total_size_2g > every_size) {
                            mListView.setSelection(total_size_2g - every_size);
                        }
                    }

                }
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            } else if (show == msg.what) {
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }else if (clear == msg.what) {
                
                if (cityTopListAdapter != null) {
                    cityTopListAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    private void startGetData(final boolean shouldFresh) {
        new Thread() {
            @Override
            public void run() {
                if (MyCommonUtil.isNetworkAviable(getApplicationContext())) {

//                    if (shouldFresh) {
                        refreshHandler.sendEmptyMessage(show);
//                    }

                    dataInit(shouldFresh);
                    refreshHandler.sendEmptyMessage(refresh);
                }
            }
        }.start();
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadBottomBar();
        choseBottomItemIndex(MyCommonConstant.TOP_ACTIVITY_CITY_INDEX);
        setTitle(R.string.bottom_city_top_new);
        setContentView(R.layout.activity_city_top);

        mNetTD = (Button) findViewById(R.id.item_net_td);
        mNet2G = (Button) findViewById(R.id.item_net_2g);
        mNetTD.setBackgroundResource(R.drawable.tabhead_actived_bak);
        mNetTD.setOnClickListener(this);
        mNet2G.setOnClickListener(this);

        tvNetSpeed = (TextView) findViewById(R.id.start_item_speed);
        tvNetSpeed.setText(getString(R.string.city_top_fix_speed) + getString(R.string.sortup));// 默认是从高到低
        tvNetSpeed.setOnClickListener(this);
        slide_item_drop_rate = (TextView) findViewById(R.id.slide_item_drop_rate);
        slide_item_signal = (TextView) findViewById(R.id.slide_item_signal);
        slide_item_call_complete = (TextView) findViewById(R.id.slide_item_call_complete);
        slide_item_drop_rate.setOnClickListener(this);
        slide_item_signal.setOnClickListener(this);

        mListView = (HVListView) findViewById(android.R.id.list);
        // 设置列头
        mListView.setmListHead((LinearLayout) findViewById(R.id.slide));

        mListView.setOnItemClickListener(onItemClickListener);

        mListView.setOnScrollListener(myOnScrollListener);

        dialog = new LoadingDialog(this);

        startGetData(false);

    }

    @Override
    protected void onStart() {
        choseBottomItemIndex(MyCommonConstant.TOP_ACTIVITY_CITY_INDEX);
        super.onStart();
    }

    /**
     * 重载abstract 接口 屏蔽重复点击bottom按钮操作
     */
    protected void responseForCityTop() {

    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String cityName = data.get(arg2).getCity_name();
            String code = MyCommonUtil.getFjCityCodeByCityName(cityName);// 和data.get(arg2).getCity_code()
                                                                         // 这个code不一样
            if (code == null || code.equals("")) {
                Intent it = new Intent(CityTopActivity.this, CellInfoActivity.class);
                it.putExtra(MyCommonConstant.CITY_NAME, cityName);
                it.putExtra(MyCommonConstant.CITY_CODE, data.get(arg2).getCity_code());
                startActivity(it);
            } else {
                Intent it = new Intent(CityTopActivity.this, GridInfoActivity.class);
                String currentUserClickCity = data.get(arg2).getCity_name();
                NetworkTestApp.getApp().setCurrentUserClickCity(currentUserClickCity);
                it.putExtra(MyCommonConstant.CITY_NAME, currentUserClickCity);
                it.putExtra(MyCommonConstant.CITY_CODE, data.get(arg2).getCity_code());
                startActivity(it);

            }
            arg0.setSelected(true);
        }
    };

    private void dataInit(boolean shouldFresh) {
        if (MyCommonUtil.isNetworkAviable(getApplicationContext())) {
            setLayoutData(shouldFresh);
        }
    }

    private void setLayoutData(boolean shouldFresh) {
        try {
            if (data != null) {
                data.clear();                
                refreshHandler.sendEmptyMessage(clear);
                
            } else {
                data = new ArrayList<CityBean>();
            }
            if (isTD) {

                CountryCityFtpInfoRankRespond respond = NetworkTestApp.getApp().getTopTDCity();
                if (shouldFresh || (respond == null)
                        || (respond.getErrorCode() != HttpConstant.CODE_SUCCESS)) {

                    respond = CountryUtil.getTop10_TD_cityAdater(CityTopActivity.this, isTop,
                            total_size_td);

                }

                if (respond != null && respond.getErrorCode() == HttpConstant.CODE_SUCCESS) {
                    service_total_size_td = respond.getTotalCount();
                    data.addAll(CountryUtil.changeTopRank(respond));
                    total_size_td=data.size();
                    NetworkTestApp.getApp().setTopTDCity(respond);
                }

                Collections.sort(data, new Comparator<CityBean>() {

                    @Override
                    public int compare(CityBean lhs, CityBean rhs) {
                        int result = -1 * (lhs.getDownSpeed() - rhs.getDownSpeed());
                        return result;
                    }

                });
            } else {

                CountryCityFtpInfoRankRespond respond = NetworkTestApp.getApp().getTop2GCity();
                if (shouldFresh || (respond == null)
                        || (respond.getErrorCode() != HttpConstant.CODE_SUCCESS)) {
                    respond = CountryUtil.getTop10_2G_cityAdater(CityTopActivity.this, isTop,
                            total_size_2g);

                }
                if (respond != null && respond.getErrorCode() == HttpConstant.CODE_SUCCESS) {
                    service_total_size_2g = respond.getTotalCount();
                    data.addAll(CountryUtil.changeTopRank(respond));
                    total_size_2g=data.size();
                    NetworkTestApp.getApp().setTop2GCity(respond);
                }

                Collections.sort(data, new Comparator<CityBean>() {

                    @Override
                    public int compare(CityBean lhs, CityBean rhs) {
                        int result = -1 * (lhs.getDownSpeed() - rhs.getDownSpeed());// 降序
                        return result;
                    }

                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        cityTopListAdapter = new CityTopListAdapter(this, data, isTD);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @SuppressWarnings("unchecked")
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_net_td: {
                mNetTD.setBackgroundResource(R.drawable.tabhead_actived_bak);
                mNet2G.setBackgroundResource(R.drawable.tabtail_normal_bak);

                isTD = true;
                isTop = true;

                startGetData(false);
            }
                break;
            case R.id.item_net_2g: {
                mNetTD.setBackgroundResource(R.drawable.tabhead_normal_bak);
                mNet2G.setBackgroundResource(R.drawable.tabtail_actived_bak);

                isTD = false;
                isTop = false;
                startGetData(false);
            }
                break;
            // 点击速率
            case R.id.start_item_speed: {
                if (data != null) {
                    if (isTop) {
                        if (isTD) {
                            Collections.sort(data, new SortCityStringSpeed(
                                    SortCityStringSpeed.DOWN, SortCityStringSpeed.cityTDSort));
                        } else {
                            Collections.sort(data, new SortCityStringSpeed(
                                    SortCityStringSpeed.DOWN, SortCityStringSpeed.city2GSort));
                        }
                        tvNetSpeed.setText(getString(R.string.city_top_fix_speed)
                                + getString(R.string.sortup));
                        isTop = false;
                    } else {
                        if (isTD) {
                            Collections.sort(data, new SortCityStringSpeed(SortCityStringSpeed.UP,
                                    SortCityStringSpeed.cityTDSort));
                        } else {
                            Collections.sort(data, new SortCityStringSpeed(SortCityStringSpeed.UP,
                                    SortCityStringSpeed.city2GSort));
                        }
                        tvNetSpeed.setText(getString(R.string.city_top_fix_speed)
                                + getString(R.string.sortdown));
                        isTop = true;

                    }
                    slide_item_drop_rate.setText(R.string.city_top_slide_drop_rate);
                    slide_item_signal.setText(R.string.city_top_slide_signal);
                    slide_item_call_complete.setText(R.string.city_top_slide_call_complete);
                    cityTopListAdapter.notifyDataSetChanged();
                }
            }
                break;
            case R.id.slide_item_drop_rate:
                if (data == null) {
                    return;
                }
                if (isDrop) {
                    Collections.sort(data, new SortCityIntSpeed(SortCityIntSpeed.UP,
                            SortCityIntSpeed.droppingRate));
                    slide_item_drop_rate.setText(getString(R.string.city_top_slide_drop_rate)
                            + getString(R.string.sortdown));
                    isDrop = false;
                } else {
                    Collections.sort(data, new SortCityIntSpeed(SortCityIntSpeed.DOWN,
                            SortCityIntSpeed.droppingRate));
                    slide_item_drop_rate.setText(getString(R.string.city_top_slide_drop_rate)
                            + getString(R.string.sortup));
                    isDrop = true;
                }
                tvNetSpeed.setText(R.string.city_top_fix_speed);
                slide_item_signal.setText(R.string.city_top_slide_signal);
                slide_item_call_complete.setText(R.string.city_top_slide_call_complete);
                cityTopListAdapter.notifyDataSetChanged();
                break;
            case R.id.slide_item_signal:
                if (data == null) {
                    return;
                }
                if (isSignal) {
                    Collections.sort(data, new SortCityIntSpeed(SortCityIntSpeed.UP,
                            SortCityIntSpeed.signalStrength));
                    slide_item_signal.setText(getString(R.string.city_top_slide_signal)
                            + getString(R.string.sortdown));
                    isSignal = false;
                } else {
                    Collections.sort(data, new SortCityIntSpeed(SortCityIntSpeed.DOWN,
                            SortCityIntSpeed.signalStrength));
                    slide_item_signal.setText(getString(R.string.city_top_slide_signal)
                            + getString(R.string.sortup));
                    isSignal = true;
                }
                tvNetSpeed.setText(R.string.city_top_fix_speed);
                slide_item_drop_rate.setText(R.string.city_top_slide_drop_rate);
                slide_item_call_complete.setText(R.string.city_top_slide_call_complete);
                cityTopListAdapter.notifyDataSetChanged();
                break;
            case R.id.slide_item_call_complete:
                if (isComplete) {
                    slide_item_call_complete
                            .setText(getString(R.string.city_top_slide_call_complete)
                                    + getString(R.string.sortdown));
                    isComplete = false;
                } else {
                    slide_item_call_complete
                            .setText(getString(R.string.city_top_slide_call_complete)
                                    + getString(R.string.sortup));
                    isComplete = true;
                }
                tvNetSpeed.setText(R.string.city_top_fix_speed);
                slide_item_drop_rate.setText(R.string.city_top_slide_drop_rate);
                slide_item_signal.setText(R.string.city_top_slide_signal);
                cityTopListAdapter.notifyDataSetChanged();
                break;
            default:
                break;

        }
    }

    @Override
    public void refresh() {
        startGetData(true);
    }

    private void addMoreData() {

        if (isTD) {
            if (total_size_td < service_total_size_td || service_total_size_td == 0) {
                total_size_td = total_size_td + every_size;
                startGetData(true);
            } else {
                MyCommonUtil.showMessage(CityTopActivity.this, R.string.data_have_all);
            }
        } else {
            if (total_size_2g < service_total_size_2g || service_total_size_2g == 0) {
                total_size_2g = total_size_2g + every_size;
                startGetData(true);
            } else {
                MyCommonUtil.showMessage(CityTopActivity.this, R.string.data_have_all);
            }
        }

    }

    private OnScrollListener myOnScrollListener = new OnScrollListener() {
        boolean isLastRow = false;

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            // 滚动时一直回调，直到停止滚动时才停止回调。单击时回调一次。
            // firstVisibleItem：当前能看见的第一个列表项ID（从0开始）
            // visibleItemCount：当前能看见的列表项个数（小半个也算）
            // totalItemCount：列表项共数

            // 判断是否滚到最后一行
            if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {
                isLastRow = true;
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // 正在滚动时回调，回调2-3次，手指没抛则回调2次。scrollState = 2的这次不回调
            // 回调顺序如下
            // 第1次：scrollState = SCROLL_STATE_TOUCH_SCROLL(1) 正在滚动
            // 第2次：scrollState = SCROLL_STATE_FLING(2) 手指做了抛的动作（手指离开屏幕前，用力滑了一下）
            // 第3次：scrollState = SCROLL_STATE_IDLE(0) 停止滚动
            // 当滚到最后一行且停止滚动时，执行加载
            if (isLastRow && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                // 加载元素
                addMoreData();
                isLastRow = false;
            }
        }
    };

}
